const db=require('../utils/mysql')
const jwt = require('jsonwebtoken')
const { v4: uuidv4 } = require('uuid');
module.exports={
    login:async (ctx,next)=>{
        console.log(112)
        let query=ctx.request.query
        let result= await new Promise((resolve,reject)=>{
            const mysql=`select * from user where username=${query.username}`
            db(mysql,(err,data)=>{
                if(err) reject(err);
                if (data.length > 0) {
                    if(data[0].password==query.password){
                        let token=jwt.sign({ username:query.username}, 'shdy344sgjxhhgegb',
                            { expiresIn:360000 })
                        resolve({
                            msg:'登录成功',
                            status:200,
                            data:{
                                token:token
                            }
                        });
                    }else {
                        resolve({
                            msg:'账号或密码错误',
                            status:201
                        });
                    }

                } else{
                        resolve({
                            msg:'账号不存在请先注册',
                            status:201
                        })

                }
            })
        })
        ctx.body=result
    },
    register:async (ctx,next)=>{
        let query=ctx.request.body
        let result= await new Promise((resolve,reject)=>{
            const mysql=`select * from user where username=${query.username}`
            const personId=uuidv4()
            const intosql=`INSERT INTO user (personId,username,password,nickname,phone,identity) 
            values ('${personId}','${query.username}',${query.password},'用户${personId.substring(0,8)}','${query.username}','user')`

            db(mysql,(err,data)=>{
                if(err) reject(err);
                if (data.length > 0) {
                    resolve({
                        msg:'账号已被占用，注册失败',
                        status:201
                    })
                } else{
                    db(intosql,(err,data)=>{
                        if(err) reject(err);
                        resolve({
                            msg:'注册成功，请返回到登陆页面',
                            status:200
                        })

                    })
                }
            })
        })
        ctx.body=result
    },
    getUserInfo:async (ctx,next)=>{
        let result= await new Promise((resolve,reject)=>{
            const mysql=`select * from user where username=${ctx.username}`
            db(mysql,(err,data)=>{
                if(err) reject(err);
                resolve({
                    msg:'登陆成功',
                    status:200,
                    data:{
                        data:data
                    }
                });
            })
        })
        ctx.body=result
    },
    loginout:()=>{

    }
}

